
import Button from "@/components/common/Button"
import TextareaAutosize from "react-textarea-autosize"
import { MdRefresh } from "react-icons/md"
import { useState,useRef } from "react"
import { PiLightbulbFill } from "react-icons/pi"
import { v4 as uuidv4 } from 'uuid'
import { Message } from "@/types/chat"
import { FiSend } from "react-icons/fi"
import { ActionType } from "@/reducers/AppReducer"
import { useAppContext } from "@/components/AppContext"

import MessageList from "./MessageList"

export default function ChatInput() {
    const [messageText, setMessageText] = useState('')
    const chatIdRef = useRef('')
    const {
      state : { messageList},
      dispatch
    } = useAppContext()
    // POST請求
    const createOrUpdateMessage = async (message:Message) => {
      const response:any = await fetch("/api/message/update", {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify(message)
      })
      console.log(response,'response===')
      if(!response.ok){
        console.log(response.statusText)
        return 
      }
      const {data } = await response.json()
      return data.message
    }
    const handSend = async () => {
      const message = await createOrUpdateMessage({
        id: " ",
        role: 'user',
        content: messageText,
        chatId: chatIdRef.current,
      })
      dispatch({type:ActionType.ADD_MESSAGE, message})
      const list = messageList.concat([message])
      doSend(list)
    }
    //  删除消息的请求
    const deleteMessage = async (id:string) => {
      const response = await fetch(`/api/message/delete?id=${id}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
      })
      if(!response.ok){
        console.log(response.statusText)
        return
      }
      const {data} = await response.json()

    }
    const doSend = async (messageList:Message[]) => {
      const body = JSON.stringify(messageList) // S
      // const messageObj:Message = {
      //   id: uuidv4(),
      //   role: 'user',
      //   content: messageText,
      // }
      // const list = messageList.concat([messageObj])
      setMessageText('')  
      const response:any = await fetch("/api/chat", {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body
      })
      if(!response.ok){
         console.log(response.statusText)
         return 
      }
      if(!response.body){
        console.log('no body')
        return 
     }
      const responseMessage: Message =  {
        id: uuidv4(),
        role: 'assistant',
        content: '',
      }
      dispatch({type:ActionType.ADD_MESSAGE, message:responseMessage})
      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let done = false
      let content = ""
      while(!done){
          const {value, done: doneReading} = await reader.read()
          done = doneReading
          const chunkValue = decoder.decode(value)
          content += chunkValue
          dispatch({type:ActionType.UPDATE_MESSAGE, message:{...responseMessage,content}})
          setMessageText(messageText + chunkValue)
      }

  }
    return (
      <div className='absolute bottom-0 w-full inset-x-0  from-gray-900'>
        <div className="w-full max-w-4xl mx-auto flex flex-col items-center px-4 speace-y-4">
          <Button
            icon={MdRefresh}
            className="font-medium mb-5"
          >
            重新生成
          </Button>
          <div className="flex p-3 mx-4 items-end w-full border border-black/10 bg-white rounded-md shadow-[0_0_15px_rgba(0,0,0,0.10)] gy-4" >
              <div className="mx-3 mb-2.5">
                  <PiLightbulbFill/>
              </div>
              <TextareaAutosize placeholder="输入一条消息..." rows={1} 
                className="flex-1 max-h-64 mb-1.5 bg-transparent text-black dark:text-white resize-none boder-none outline-none"
                value={messageText}
                onChange={(e) => setMessageText(e.target.value)}
              />
              <Button icon={FiSend} className="mx-3 !rounded-lg" onClick={handSend}/>
          </div>
          <footer className="text-center text-gsm  text-gray-700 mt-4 text-sm">
            @{new Date().getFullYear()}
          </footer>
        </div>
      </div>
    )
}